<?php
/**
 * 商户管理控制器
 * @author 孙银川
 * @date   2017.12.20
 */

namespace app\admin\controller;
use app\common\model\Shop as Shops;
use app\common\model\DataExport;
use app\common\model\Types;

class Shop extends Base{


    /**
     * 店铺分类浏览
     * @return mixed
     */
    public function shoptype(){
        $list = Types::order('ty_sort','asc')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    /**
     * 添加店铺分类表单
     * @return mixed
     */
    public function add_type(){
        return $this->fetch();
    }

    /**
     * 提交添加
     */
    public function submit_type(){
        $param = $this->request->param();
        $file = $this->request->file('file');
        $info = $file->validate(['ext'=>'jpg,png,gif,jpeg'])->move( 'public/upload/xcxadmin');
        if(!$info){
            return $this->error('添加失败！失败原因'.$file->getError());
        }
        $param['ty_ico'] = $info->getPathName();
        $query = Types::create($param);
        if($query){
            $this->success($query->ty_name.'添加成功！',url('shop/shoptype'),'',1);
        }else{
            return $this->error('添加失败，请重新添加');
        }
    }

    /**
     * ajax 修改商户类别
     */
    public function cateAjax(){
        $id = $this->request->post('id');
        $val = $this->request->post('val');
        $act = $this->request->post('act');
        $query = Types::where('ty_id',$id)->update([$act=>$val]);
        if($query){
            return $this->success('修改成功');
        }else{
            return $this->error('修改失败');
        }
    }

    /**
     * 删除
     */
    public function del_type(){
        $id = $this->request->post('id');
        $query = Types::destroy($id);
        if($query){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }
    }

    /**
     * 类别图片修改
     */
    public function upload_type(){
        $id = $this->request->post('id');
        if($file = $this->request->file('file')){
            $info = $file->validate(['ext'=>'jpg,png,gif,jpeg'])->move( 'public/upload/xcxadmin');
            if(!$info){
                return $this->error('添加失败！失败原因'.$file->getError());
            }
            $type = Types::get($id);
            $ico = $type['ty_ico'];
            $type->ty_ico = $info->getPathName();
            $query = $type->isUpdate(true)->save();
            if($query){
                if(is_file($ico)){
                    unlink($ico);
                }
                return $this->success('修改成功',url('shop/shoptype'),'',1);
            }else{
                return $this->error('修改失败！');
            }
        }
        return $this->error('请上传图片',url('shop/shoptype'),'',1);
    }


	/**
     * 添加商户
     */
	public function shopAdd(){
		$shops = new Shops();
		// 提交表单
		if(input('get.act') == 'a'){
			$data = input('post.');
			// 图片上传
			if(isset($_FILES['image']['name']) && $_FILES['image']['name']){
				$file = request()->file('image');
				$info = $file->move("public/upload/shop");
				if($info){
					$save_name = $info->getPathName();
					if($save_name) $data['sp_bus_license_url'] = $save_name;
				}else{
					echo $file->getError();
				}
			}
			if($data['sp_name']){
				$data['sp_create_time'] = time();
				// 生成店铺编号
				$data['sp_number'] = $shops->shopNum();		
				$res = $shops->add($data);
				if($res){
					$this->success('添加成功','shopList');
				}else{
					$this->error('添加失败','shopList');
				}
			}
		}else{
			// 获取所有的商户分类
			$cates = $shops->cates();
			// 获取所有的代理商
			$agents = $shops->agent();
		}

		$this->assign('cates',$cates);
		$this->assign('agents',$agents);
		return $this->fetch('shop/shopAdd');
	}

	/**
     * 商户列表
     */
	public function shopList(){
		// 代理商ID下的商户
		if($agem_id = input('param.agem_id')) $map['sp_agem_id'] = ['s.sp_agem_id','=',$agem_id];
		// 已审核
		$map['sp_audit'] = ['s.sp_audit','=',1];
		// 搜索
		if($param = input('param.')){
			// 查询条件
			if(!empty($param['name'])) $map['sp_name'] = ['s.sp_name','like','%'.$param['name'].'%'];
			if(!empty($param['mobile'])) $map['sp_mobile'] = ['s.sp_mobile','like','%'.$param['mobile'].'%'];
			if(!empty($param['agent_id'])) $map['sp_agem_id'] = ['s.sp_agem_id','=',$param['agent_id']];
			if(!empty($param['cate_id'])) $map['sp_tyid'] = ['s.sp_tyid','=',$param['cate_id']];
			if(isset($param['pages'])) unset($param['pages']);
		}else{
			$param = [];
		}

		$shops = new Shops();
		$data = $shops->enquiries(20,$map,$param);
		$shop_list = $data->items();
		foreach($shop_list as $k=>$v){
			// 商户状态
			switch($v['sp_status']){
				case 1: $shop_list[$k]['sp_status']='正常'; break;
				case 2: $shop_list[$k]['sp_status']='禁用'; break;
				case 3: $shop_list[$k]['sp_status']='已删除'; break;
			}
			// 登录时间
			$shop_list[$k]['sp_login_time'] = date('Y-m-d H:i:s',$v['sp_login_time']);
			// 添加时间
			$shop_list[$k]['sp_create_time'] = date('Y-m-d H:i:s',$v['sp_create_time']);
		}

		// 获取所有商户分类
		$cates = $shops->cates();
		// 获取所有代理商
		$agents = $shops->agent();

		// 导出excel表格
		if(input('get.act') == 'ep'){
			$dmodel = new DataExport();
			// 标题行
        	$title = array('商户ID','商户名称','手机号','登录账号','店主姓名','店铺电话','区域','商户分类','代理商','状态','APPID','OpenID','最近登录时间','注册时间');
			$res = $dmodel->export($shop_list,$title,'商户数据列表');
		}

		$this->assign('page',$data->page);
		$this->assign('count',$data->count);
		$this->assign('cates',$cates);
		$this->assign('agents',$agents);
		$this->assign('param',$param);
		$this->assign('shop_list',$shop_list);
		return $this->fetch('shop/shopList');
	}

	/**
     * 商户详情
     */
	public function shopDetail(){
		$id = input('param.id');
		// 获取商户信息
		$shops = new Shops();
		if($id) $shop = $shops->detail($id);

		$this->assign('shop',$shop);
		return $this->fetch('shop/shopDetail');
	}

	/**
     * 待审核商户 sp_audit=0
     */
	public function shopAudit(){
		$shops = new Shops();
		$map['sp_audit'] = ['s.sp_audit','<=',0];
		$shop_list = $shops->enquiries(20,$map);

		$this->assign('page',$shop_list->page);
		$this->assign('count',$shop_list->count);
		$this->assign('shop_list',$shop_list->items());
		return $this->fetch('shop/shopAudit');
	}

	/**
     * 修改商户
     */
	public function shopUpd(){
		// 商户ID
		$id = input('param.id');
		$shops = new Shops();

		// 提交修改
		if(input('get.act') == 'u'){
			$data = input('post.');
			cookie('id',$data['sp_id']);
			$id = cookie('id');

			// 执行修改
			if($data['sp_id']){
				// 图片上传
				if(isset($_FILES['image']['name']) && $_FILES['image']['name']){
					$file = request()->file('image');
					$info = $file->move("public/upload/shop");
					if($info){
						$save_name = $info->getPathName();
						if($save_name) $data['sp_bus_license_url'] = $save_name;
					}else{
						echo $file->getError();
					}
				}
				// 审核时间
				if(isset($data['sp_audit'])) $data['sp_audit_time'] = time();
				$res = $shops->edit($data);
				if($res){
					$this->success('修改成功','shopUpd?id='.$id);
				}else{
					$this->error('修改失败','shopUpd?id='.$id);
				}
			}else{
				$this->error('缺少ID参数','shopUpd?id='.$id);
			}
		}elseif($id){
			// 商户信息
			$shop = $shops->detail($id);
			// 获取所有的商户分类
			$cates = $shops->cates();
			// 获取所有的代理商
			$agents = $shops->agent();

			$this->assign('shop',$shop);
			$this->assign('cates',$cates);
			$this->assign('agents',$agents);
		}

		return $this->fetch('shop/shopUpd');
	}

	/**
     * 商户提现记录
     */
	public function cashList(){
		// 搜索条件
		$map = array();
		// 表单提交
		if(input('get.act') == 's'){
			$data = input('post.');
			$map[] = ['c.c_status','=',$data['c_status']];
			if($data['sp_name']) $map[] = ['s.sp_name','like','%'.$data['sp_name'].'%'];
			if($data['c_order']) $map[] = ['c.c_order','like','%'.$data['c_order'].'%'];
			if($data['s_time']) $map[] = ['c.start_time','>=',strtotime($data['s_time'])];
		}
		
		$shops = new Shops();
		$cashes = $shops->cash(20,$map);

		$this->assign('page',$cashes->page);
		$this->assign('count',$cashes->count);
		$this->assign('cashes',$cashes->items());
		return $this->fetch('shop/cashList');
	}

	/**
     * 商户提现详情
     */
	public function cashDetail(){
		if($id = input('get.id')){
			$cash = db('cash_with')->alias('c')->join('shops s','s.sp_id=c.shop_id')->field('c.*,s.sp_name')->where('c_id='.$id)->find();

			$this->assign('cash',$cash);
		}
		return $this->fetch('shop/cashDetail');
	}

	/**
     * ajax提现审核
     */
	public function cashAjax(){
		$data = input('post.');
		if($data['c_id']){
			// 结束时间
			$data['end_time'] = time();
			$res = db('cash_with')->update($data);
		}
		if($res){
			return 1;
		}else{
			return 0;
		}
	}

	/**
     * 删除商户 sp_status=3
     */
	public function shopDel(){
		$id = input('param.id');
		$shops = new Shops;
		$res = 0;
		if($id){
			$data['sp_id'] = $id;
			$data['sp_status'] = 3;
			$res = $shops->edit($data);
		}
		return $res;
	}
}
?>